import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

import { baseRequestClient, requestClient } from '#/api/request';
import websiteConfig from '#/constant/website';
import { encrypt } from '#/utils';

import 'dayjs/locale/en';
// 扩展utc插件
dayjs.extend(utc);

export namespace AuthApi {
  /** 登录接口参数 */
  export interface LoginParams {
    authKey?: string;
    authType?: number;
  }

  /** 登录接口返回值 */
  export interface LoginResult {
    token: string;
  }

  export interface RefreshTokenResult {
    data: string;
    status: number;
  }
}

/**
 * 登录
 */
export async function loginApi(params: AuthApi.LoginParams) {
  const signDate = dayjs().locale('en').utc().format('ddd,YYMMDDThhmmssSSS ZZ');
  const headers = { [websiteConfig.signDataHeader]: signDate };
  params.authKey = encrypt(params.authKey as string, signDate);
  return requestClient.get<AuthApi.LoginResult>('/auth/grant', params, {
    headers,
  });
}

/**
 * 刷新accessToken
 */
export async function refreshTokenApi() {
  return baseRequestClient.post<AuthApi.RefreshTokenResult>('/auth/refresh', {
    withCredentials: true,
  });
}

/**
 * 退出登录
 */
export async function logoutApi() {
  return baseRequestClient.post('/auth/logout', {
    withCredentials: true,
  });
}

/**
 * 获取用户权限码
 */
export async function getAccessCodesApi() {
  return requestClient.get<string[]>('/auth/codes');
}
